//
//  SleepController.m
//  SleepingElf
//
//  Created by karong on 2023/10/13.
//

#import "SleepController.h"
#import "UIButton+ImageAlign.h"
#import <Lottie.h>
#import "UIImage+GIF.h"
#import "SleepRequest.h"
#import "SleepModel.h"
#import "ClassListPop.h"
#import "HomeRequest.h"

@interface SleepController () <UIPickerViewDelegate, UIPickerViewDataSource>
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *miniTitle;
@property (weak, nonatomic) IBOutlet UILabel *subTitleLabel;
@property (weak, nonatomic) IBOutlet UIView *musicView;
@property (weak, nonatomic) IBOutlet UIButton *wakeUpBtn;
@property (weak, nonatomic) IBOutlet UIView *lottieView;
@property (weak, nonatomic) IBOutlet UIImageView *musicBGImageView;
@property (weak, nonatomic) IBOutlet UIImageView *musicDefaultImageView;

@property (strong, nonatomic) IBOutletCollection(UIImageView) NSArray *imageViewArray;
@property (weak, nonatomic) IBOutlet UILabel *togeterLabel;
@property (weak, nonatomic) IBOutlet UIView *togeterView;
@property (weak, nonatomic) IBOutlet UIButton *playBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titleLabelTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *musicViewTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *musicViewBottom;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *waveViewBottom;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lockTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lockBottom;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *timeTop;

@property (weak, nonatomic) IBOutlet YYAnimatedImageView *animationImageView;
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
@property (weak, nonatomic) IBOutlet UIView *defaultView;
@property (weak, nonatomic) IBOutlet UILabel *toastLabel;
@property (weak, nonatomic) IBOutlet UILabel *wakeUpLabel;
@property (weak, nonatomic) IBOutlet UIButton *collectBtn;
@property (weak, nonatomic) IBOutlet UILabel *wakeUpTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *runTimeLabel;
@property (strong, nonatomic) IBOutletCollection(UIImageView) NSArray *imageArray;
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, strong) LOTAnimationView * animation;
@property (nonatomic, strong) NSArray * hourArray;
@property (nonatomic, strong) NSArray * minArray;
@property (nonatomic, strong) NSArray * musicArray;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, assign) NSInteger t;//用于计算长按了多久
@end

@implementation SleepController

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.hidesBottomBarWhenPushed = NO;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self layoutPlayStatus:[[PlayerManager shared] isPlaying]];
    [self layoutMusicsName];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self layoutLeftTopView:[[PlayerManager shared] isPlaying]];
    });
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.wakeUpBtn setButtonImageTitleStyle:(GRButtonImageTitleStyleLeft) padding:4];
    [self layoutDevice];
    [self layoutAnimation];
    [self loadSleepAndRelaxListRequest];
    self.selectIndex = floor((self.hourArray.count / 2.0f));
    [self layoutWakeUpTime:self.selectIndex];
    [self.pickerView selectRow:self.selectIndex inComponent:0 animated:NO];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.pickerView.subviews[1].backgroundColor = UIColor.clearColor;
    });
    [self addObserver];
}

- (void)addObserver {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshMusicInfo) name:SERefreshMusicNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keepTimeChangeNotification:) name:SEKeepTimeChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshMusicInfo) name:SESleepSettingNotification object:nil];
}

- (void)keepTimeChangeNotification:(NSNotification*)notification {
    NSInteger time = [[notification object] integerValue];
    if (time > 0) {
        self.runTimeLabel.text = SESF(@"%@/%@", [self getMMSSFromSS:time], [self getMMSSFromSS:appConfig.sleepConfig.time]);
    }
    else if (time == 0) {
        self.defaultView.hidden = NO;
    }
}

- (void)layoutMusicsName {
    for (int i = 0; i < 3; i++) {
        UIImageView * img = self.imageArray[i];
        if (appConfig.lastMusicArray.count > 1 && i < appConfig.lastMusicArray.count) {
            MusicModel * music = appConfig.lastMusicArray[i];
            [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:music.cover] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                if (image) {
                    image = [image imageWithRenderingMode:(UIImageRenderingModeAlwaysTemplate)];
                    img.image = image;
                    img.tintColor = [UIColor colorFromHexRGB:@"ffffff"];
                }
            }];
        }
        else {
            img.image = nil;
        }
    }
}

- (void)layoutWakeUpTime:(NSInteger)index {
    NSInteger hour = [self.hourArray[index] integerValue];
    NSInteger minte = [self.minArray[index] integerValue];
    NSString * hourStr = hour>0?SESF(WSLocalized(@"%ld小时"), hour):@"";
    NSString * minteStr = minte>0?SESF(WSLocalized(@"%ld分钟"), minte):@"";
    self.wakeUpLabel.text = SESF(WSLocalized(@"唤醒时间：%@%@"), hourStr, minteStr);
    self.wakeUpTimeLabel.text = SESF(WSLocalized(@"%@%@后唤醒"), hourStr, minteStr);
}

- (void)refreshMusicInfo {
    [self layoutPlayStatus:[[PlayerManager shared] isPlaying]];
    [self layoutMusicsName];
}

- (void)layoutPlayStatus:(BOOL)play {
    self.playBtn.selected = play;
    play?[self.animation play]:[self.animation pause];
    play?[[PlayerManager shared]resume]:[[PlayerManager shared]pause];
    self.musicDefaultImageView.hidden = play;
    self.animation.hidden = !play;
    self.titleLabel.text = [[PlayerManager shared] currentPlayingMusic].title;
    self.miniTitle.text = [[PlayerManager shared] currentPlayingMusic].title;
    self.collectBtn.selected = appUserCenter.isLogin?[[PlayerManager shared] currentPlayingMusic].is_collect:NO;
}

- (void)layoutLeftTopView:(BOOL)play {
    if (play) {
        [self.miniTitle.layer removeAllAnimations];
        [self.miniTitle sizeToFit];
        CGRect frame = self.miniTitle.frame;
        frame.origin.x = 0;
        self.miniTitle.frame = frame;
        [UIView beginAnimations:@"miniTitleAnimation" context:NULL];
        [UIView setAnimationDuration:8.8f];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationRepeatAutoreverses:NO];
        [UIView setAnimationRepeatCount:999999];
        frame.origin.x = -frame.size.width;
        self.miniTitle.frame = frame;
        [UIView commitAnimations];
        self.animationImageView.image = [YYImage imageNamed:@"yinfuAnimation.gif"];
        [self.animationImageView startAnimating];
    }
    else {
        [self.animationImageView stopAnimating];
        [self.miniTitle.layer removeAllAnimations];
        CGRect frame = self.miniTitle.frame;
        frame.origin.x = 0;
        self.miniTitle.frame = frame;
    }
}

- (void)layoutTogeter:(NSArray *)imageArray {
    if (imageArray.count > 0) {
        self.togeterView.hidden = NO;
        for (int i = 0; i < self.imageViewArray.count; i++) {
            UIImageView * image = self.imageViewArray[i];
            if (i < imageArray.count) {
                NSString * imageUrl = imageArray[i];
                [image sd_setImageWithURL:[NSURL URLWithString:SEEmptyStr(imageUrl)] placeholderImage:SEUserPlaceholderImage];
                [self.togeterView bringSubviewToFront:image];
            }
            else {
                image.image = nil;
            }
        }
        
    }
    else {
        self.togeterView.hidden = YES;
    }
}

-  (void)layoutDevice {
    self.titleLabelTop.constant = SEIsiPhoneX?100:52;
    self.musicViewTop.constant = SEIsiPhoneX?34:28;
    self.musicViewBottom.constant = SEIsiPhoneX?52:28;
    self.waveViewBottom.constant = SEIsiPhoneX?12.3:11;
    self.lockTop.constant = SEIsiPhoneX?8:10;
    self.lockBottom.constant = SEIsiPhoneX?56:32;
    self.timeTop.constant = SEIsiPhoneX?55:29;
    [self.togeterView uploadLayout];
}

- (void)layoutAnimation {
    UIImage * img = SEIMG(@"bg_wave");
    CGSize size = img.size;
    size.width += SEIsiPhoneX?80:40;
    size.height += SEIsiPhoneX?80:40;
    NSString * path = [[NSBundle mainBundle] pathForResource:@"musicWavePng" ofType:@"png"];
    NSData * gifData = [NSData dataWithContentsOfFile:path];
    UIImage * gifImage = [UIImage sd_imageWithGIFData:gifData];
    UIImageView * gifImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, img.size.width, img.size.height)];
    gifImageView.image = gifImage;
    [self.view insertSubview:gifImageView belowSubview:self.musicView];
    [gifImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.musicView).offset(2);
        make.centerY.mas_equalTo(self.musicView);
        make.size.mas_offset(size);
    }];
    self.animation = [LOTAnimationView animationNamed:@"musicWave_lottie"];
    self.animation.frame = CGRectMake(0, 0, self.lottieView.size.width, self.lottieView.size.height);
    self.animation.loopAnimation = YES;
    [self.lottieView addSubview:self.animation];
    [self.animation play];
    if (SEIsiPhoneX) {
        self.waveViewBottom.constant = 15.0f;
        [self.musicView uploadLayout];
    }
}

- (void)loadTipAndListen {
    [SleepRequest loadTipAndListenListWithSuccess:^(id obj) {
        SleepModel * sleepModel = obj;
        self.subTitleLabel.text = SEEmptyStr(sleepModel.tip);
        [self layoutTogeter:sleepModel.avatarList];
        self.togeterLabel.text = SESF(WSLocalized(@"%ld人一起听歌入睡"), (long)sleepModel.listenNum);
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)loadSleepAndRelaxListRequest {
    [HomeRequest loadHomeSleepAndRelaxWithPage:1 pageSize:50 success:^(NSArray *array) {
        self.musicArray = array;
        if (array.count > 0) {
            [[PlayerManager shared] defaultMusic:array.firstObject];
            [self layoutPlayStatus:[[PlayerManager shared] isPlaying]];
            [self layoutLeftTopView:[[PlayerManager shared] isPlaying]];
        }
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
    }];
}

- (void)collectRequest:(MusicModel *)music {
    [SleepRequest collectMusicWithMusic_id:music.id success:^{
        music.is_collect = YES;
        [self layoutPlayStatus:[[PlayerManager shared] isPlaying]];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)deleteCollectRequest:(MusicModel *)music {
    [SleepRequest deleteCollectMusicWithMusic_id:music.id success:^{
        music.is_collect = NO;
        [self layoutPlayStatus:[[PlayerManager shared] isPlaying]];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)collectCustomMusicRequest:(NSString *)title {
    [SleepRequest collectCustomMusicWithMusicArray:appConfig.lastMusicArray title:title success:^{
        [[PlayerManager shared]currentPlayingMusic].is_collect = YES;
        [self layoutPlayStatus:[[PlayerManager shared] isPlaying]];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}


- (IBAction)collectAction:(UIButton *)sender {
    WeakSelf
    if (appUserCenter.isLogin) {
        if (sender.selected) {
            if (appConfig.lastMusicArray.count > 1) {
                ///这里没有拿不到专属白噪音的id，没办法删除
                [SEToast simple:WSLocalized(@"暂时无法删除")];
            }
            else {
                [self deleteCollectRequest:[PlayerManager shared].currentPlayingMusic];
            }
        }
        else {
            if (appConfig.lastMusicArray.count > 1) {
                UIViewController * target = [[CTMediator sharedInstance]ct_showTFAlterWithTitle:@"设置专属音频名称" content:@"" placeholderStr:WSLocalized(@"请输入音频名称") maxWordCount:15 confirm:@"" confirmHandle:^(NSString *string) {
                    [weakSelf collectCustomMusicRequest:string];
                } cancel:@""];
                target.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                target.modalPresentationStyle = UIModalPresentationCustom;
                [self presentViewController:target animated:YES completion:nil];
            }
            else {
                [self collectRequest:[PlayerManager shared].currentPlayingMusic];
            }
        }
    }
    else {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"LoginController" bundle:nil];
        UIViewController * target = [storyBoard instantiateViewControllerWithIdentifier:@"MiniLoginPop"];
        [self presentViewController:target animated:YES completion:nil];
    }
}

- (IBAction)playAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    [self layoutPlayStatus:sender.selected];
    [self layoutLeftTopView:sender.selected];
}

- (IBAction)startSleepAction:(UIButton *)sender {
    [self loadTipAndListen];
    self.defaultView.hidden = YES;
    appConfig.wakeUpType = 2;
    appConfig.sleepConfig.time = 10;//(self.selectIndex + 1) * 15 * 60;
    [appConfig.sleepConfig starTimeKeeper];
}

- (IBAction)endSleepTouchUpInside:(id)sender {
    if (self.t > 0) {
        [self.timer invalidate];
        self.timer = nil;
        self.toastLabel.hidden = YES;
    }
}

- (IBAction)endSleepTouchDown:(id)sender {
    [self.timer fire];

}

- (IBAction)classListAction:(id)sender {
    ClassListPop * target = [self.storyboard instantiateViewControllerWithIdentifier:@"ClassListPop"];
    [self presentViewController:target animated:YES completion:nil];
}

- (IBAction)randomMusic:(id)sender {
    if (self.musicArray.count > 0) {
        NSInteger index = arc4random()%self.musicArray.count;
        [[PlayerManager shared]playWithMusic:self.musicArray[index]];
        [self layoutPlayStatus:[[PlayerManager shared] isPlaying]];
        [self layoutLeftTopView:[[PlayerManager shared] isPlaying]];
    }
    else {
        [SEToast simple:WSLocalized(@"网络繁忙，轻稍后再试")];
        [self loadSleepAndRelaxListRequest];
    }
}

- (IBAction)myCollectAction:(id)sender {
    if (appUserCenter.isLogin) {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MeController" bundle:nil];
        UIViewController * target = [storyBoard instantiateViewControllerWithIdentifier:@"CollectController"];
        [self.navigationController pushViewController:target animated:YES];
    }
    else {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"LoginController" bundle:nil];
        UIViewController * target = [storyBoard instantiateViewControllerWithIdentifier:@"MiniLoginPop"];
        [self presentViewController:target animated:YES completion:nil];
    }
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.hourArray.count;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    return 190;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 101;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    NSString * text = SESF(@"%@:%@", self.hourArray[row], self.minArray[row]);
    UIColor *  color = [UIColor colorFromHexRGB:@"ffffff"];
    UILabel *label = [[UILabel alloc]init];
    label.textAlignment = 1;
    label.font = [UIFont systemFontOfSize:70];
    label.textColor = color;
    label.text = text;
    return label;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    self.selectIndex = row;
    [pickerView reloadComponent:component];
    [self layoutWakeUpTime:row];
}

// 毫秒转时分秒
-(NSString *)getMMSSFromSS:(NSInteger)totalTime{
    
    NSInteger seconds = totalTime;
    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",seconds/3600];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
    NSString *format_time = @"";

        format_time = SESF(@"%@:%@",str_hour,str_minute);
    return format_time;
    
}

- (NSArray *)hourArray {
    if (!_hourArray) {
        _hourArray = [self timeArray];
    }
    return _hourArray;
}

- (NSArray *)timeArray {
    NSMutableArray * hArray = [NSMutableArray new];
    NSMutableArray * mArray = [NSMutableArray new];
    for (int i = 0; i < 24; i++) {
        for (int j = 0; j < 4; j++) {
            [hArray addObject:SESF(@"%02d", i)];
            [mArray addObject:SESF(@"%02d", j*15)];
        }
    }
    [hArray removeFirstObject];
    [mArray removeFirstObject];
    self.minArray = mArray;
    return hArray;
}

- (NSTimer *)timer {
    if (!_timer) {
        self.t = 0;
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
    return _timer;
}

- (void)timerAction {
    if (self.t >= 3) {
        self.toastLabel.hidden = YES;
        self.defaultView.hidden = NO;
        [self.timer invalidate];
        self.timer = nil;
        appConfig.wakeUpType = 0;
        [appConfig defaultTimeKeeper];
    }
    else {
        self.toastLabel.hidden = NO;
        self.toastLabel.text = SESF(WSLocalized(@"%ldS后取消"), 3 - self.t);
    }
    self.t++;
}
@end
